import { Component, Input, ViewChild, ElementRef, HostListener } from '@angular/core';
import { CompanyHeaderService } from "./companyHeader.service";
import { CompanyModel } from '../../company.model';
import { ModalComponent } from '../../../../../shared/components/modal/modal.component';
import { SearchComponent } from '../../../../../shared/components/search/search.component';
import { UtilsService } from '../../../../../shared/services/utils.service';
import { AppComponent } from '../../../../../app.component';

/**
 * Company header main component
 *
 * Author: Sorin Spiru
 * Date: 13.02.2018
 */
@Component({
    selector: 'company-header',
    templateUrl: 'companyHeader.component.html',
    styleUrls: ['./companyHeader.component.scss']
})
export class CompanyHeaderComponent {
    @Input() company: CompanyModel;

    @Input() addPortfolio: boolean;

    @ViewChild('addToPortfolio') addToPortfolio: ModalComponent;

    @ViewChild('addToPortfolioSearch') addToPortfolioSearch: SearchComponent;

    @ViewChild('stickyContainer') stickyContainer: ElementRef;
    @ViewChild('otherCompanyContainer') otherCompanyContainer: ElementRef;

    @HostListener('window:scroll', [])
    onWindowScroll() {
        if (window.pageYOffset > 70 + (this.otherCompanyContainer ? 110 : 0)) {
            this.stickyContainer.nativeElement.classList.add('affix');
        } else {
            this.stickyContainer.nativeElement.classList.remove('affix');
        }
    }

    constructor(
        private companyHeaderService: CompanyHeaderService,
        private rootComponent: AppComponent
    ) { }

    /* START - add company to portfolio */
    public saveAddToPortfolio(): void {
        this.companyHeaderService
            .addCompanyToPortfolio(this.addToPortfolioSearch.selected.id, this.company.id)
            .subscribe(result => {
                if (result && result.indexOf("5103") != -1) {
                    this.rootComponent.showSuccess('The company added to the selected portfolio successfully');
                    this.rootComponent.showWarning('The company already exists in the selected portfolio');
                } else {
                    this.rootComponent.showSuccess('The company added to the selected portfolio successfully');
                }
                this.closeAddToPortfolio();
            });
    }

    public cancelAddToPortfolio(): void {
        this.closeAddToPortfolio();
    }

    private closeAddToPortfolio(): void {
        this.addToPortfolioSearch.term = '';
        this.addToPortfolioSearch.found = [];
        this.addToPortfolioSearch.selected = null;
        this.addToPortfolio.hide();
    }
    /* END - add company to portfolio */
}
